const express = require("express");
const bodyParser = require("body-parser");
const fileUpload = require("express-fileupload");
const { resolve, extname } = require("path");
const { existsSync, appendFileSync, writeFileSync, mkdirSync } = require("fs");

const app = express();
const PORT = "5454";

// 跨域
app.all("*", (req, res, next) => {
  res.header("Access-Control-Allow-origin", "*");
  res.header("Access-Control-Allow-Methods", "POST,GET");
  next();
});

app.use(bodyParser.json());
app.use(fileUpload());
app.use('/',express.static('upload'))

// app.get("/", (req, res) => {
//   res.send("Hello World!");
// });

app.post("/upload", (req, res) => {
  const { name, size, type, offset, hash } = req.body;
  const { file } = req.files;
  // console.log(name, size, type, offset, hash);
  //取后缀
  let ext = extname(name);
  let fileName = resolve(__dirname, "./upload/" + hash + ext);
  if (offset != 0) {
    if (!existsSync(fileName)) {
      res.status(400).send({
        msg:'文件不存在'
      })
      return
    }
    appendFileSync(fileName,file.data)
    res.send({
      code:200,
      data:'http://localhost:5454/' + fileName,
      msg:'文件写入成功'
    })
    return
  }
  writeFileSync(fileName, file.data);
    res.send({
      code: 200,
      msg: "文件创建并写入成功",
    });
});

app.listen(PORT, () => {
  console.log(`server running in ${PORT}`);
});
